﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using SpectrEngine.Framework;

namespace CellWarzGame.Collections
{
    internal sealed class CellDistanceComparer
        : IComparer<DrawableGameNode>
    {
        private Vector2 distanceToTest;

        public CellDistanceComparer(Vector2 distanceToTest)
        {
            this.distanceToTest = distanceToTest;
        }

        public int Compare(DrawableGameNode x, DrawableGameNode y)
        {
            return Vector2.DistanceSquared(distanceToTest, x.Position).CompareTo(
                Vector2.DistanceSquared(distanceToTest, y.Position));
        }
    }

    public class CellList
        : HashSet<DrawableGameNode>, ICellListService
    {

        public CellList(Game game)
        {
            this.game = game;

            game.Services.AddService(typeof(ICellListService), this);
        }

        private Game game;

        public IList<DrawableGameNode> GetNearest(Vector2 position)
        {
            List<DrawableGameNode> itemsFound = new List<DrawableGameNode>();
            CellDistanceComparer comparer = new CellDistanceComparer(position);

            itemsFound.AddRange(this);

            itemsFound.Sort(comparer);

            return itemsFound;
        }

        public void Register(DrawableGameNode node)
        {
            node.Disposed += new EventHandler(node_Disposed);
            this.Add(node);
        }

        void node_Disposed(object sender, EventArgs e)
        {
            this.Remove((DrawableGameNode)sender);
        }
    }
}
